import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Notification } from '../types/notification'
import { notificationService } from '../services/notification.service'

export const useNotificationStore = defineStore('notification', () => {
  const notifications = ref<Notification[]>([])
  
  // 计算未读通知数量
  const unreadCount = computed(() => {
    return notifications.value.filter(notification => !notification.read).length
  })

  // 获取所有通知
  const fetchNotifications = async () => {
    try {
      const response = await notificationService.getNotifications()
      notifications.value = response
    } catch (error) {
      console.error('Failed to fetch notifications:', error)
    }
  }

  // 标记单个通知为已读
  const markAsRead = async (notificationId: string) => {
    try {
      await notificationService.markAsRead(notificationId)
      const notification = notifications.value.find(n => n.id === notificationId)
      if (notification) {
        notification.read = true
      }
    } catch (error) {
      console.error('Failed to mark notification as read:', error)
    }
  }

  // 标记所有通知为已读
  const markAllAsRead = async () => {
    try {
      await notificationService.markAllAsRead()
      notifications.value.forEach(notification => {
        notification.read = true
      })
    } catch (error) {
      console.error('Failed to mark all notifications as read:', error)
    }
  }

  // 添加新通知
  const addNotification = (notification: Notification) => {
    notifications.value.unshift(notification)
  }

  return {
    notifications,
    unreadCount,
    fetchNotifications,
    markAsRead,
    markAllAsRead,
    addNotification
  }
})